import socket
from tkinter import *
from threading import Thread

# socket 接入
HOST = '127.0.0.1'
PORT = 8888


def get_msg():
    while True:
        try:
            msg = s_client.recv(1024).decode('utf8')
            text_msg.insert(END, msg)
        except :
            break


def send_msg():
    message = text_text.get('0.0', END)
    s_client.send(bytes(message, 'utf-8'))
    print('sent message')
    text_text.delete('0.0', END)


talk = Tk()
talk.title('HandsomeB talk room')
msg_frame = Frame(width=480, height=300, bg='white')
text_frame = Frame(width=480, height=100)
send_frame = Frame(width=480, height=30)

text_msg = Text(msg_frame)
text_text = Text(text_frame)
button_send = Button(send_frame, text='发送', command=send_msg)

# 容器位置排放
msg_frame.grid(row=0, column=0, padx=3, pady=6)
text_frame.grid(row=1, column=0, padx=3, pady=6)
send_frame.grid(row=2, column=0)

# 容器大小固定
msg_frame.grid_propagate(0)
text_frame.grid_propagate(0)
send_frame.grid_propagate(0)

# 文本按键添加到容器中
text_msg.grid()
text_text.grid()
button_send.grid()

s_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_client.connect((HOST, PORT))

receive_thread = Thread(target=get_msg)
receive_thread.start()
talk.mainloop()
